/**
 * 面包屑控制中心
 */
import pathToRegexp from 'path-to-regexp';
import menu from '../configs/menus';
import { queryDeepArray } from '../utils/share';

class BreadProvider {
  constructor() {
    this.caches = {};
    this.bread = {
      pathArray: [],
      paramMap: {}
    };
  }

  getBread(pathname) {
    if (this.caches[pathname]) {
      return this.caches[pathname];
    }
    const pathArray = [];
    let current = null;
    function getCurrent(menus) {
      for (let i = 0; i < menus.length; i += 1) {
        const item = menus[i];
        if (item.route && pathToRegexp(item.route).exec(pathname)) {
          current = item;
          break;
        }
        if (item.children) {
          getCurrent(item.children);
        }
      }
    }
    getCurrent(menu);
    const getPathArray = (item) => {
      pathArray.unshift(item);
      if (item && item.pname) {
        getPathArray(queryDeepArray(menu, item.pname, 'name'));
      }
    };

    const paramMap = {};
    if (!current) {
      pathArray.push(menu[0] || {
        id: 1,
        icon: 'laptop',
        name: 'Dashboard'
      });
      pathArray.push({
        id: 404,
        name: 'Not Found'
      });
    } else {
      getPathArray(current);

      const keys = [];
      const values = pathToRegexp(current.route, keys).exec(pathname.replace('#', ''));
      if (keys.length) {
        keys.forEach((currentValue, index) => {
          if (typeof currentValue.name !== 'string') {
            return;
          }
          paramMap[currentValue.name] = values[index + 1];
        });
      }
    }
    if (current && current.pathArray) {
      this.bread = {
        pathArray: current.pathArray,
        paramMap
      };
    } else {
      this.bread = {
        pathArray,
        paramMap
      };
    }
    this.caches[pathname] = this.bread;
    return this.bread;
  }
  setBread(pathname, pathArray, paramMap = {}) {
    this.caches[pathname] = {
      pathArray,
      paramMap
    };
  }
}

export const breadProvider = new BreadProvider();
